//
//  XJBaseVC.swift
//  XJCameraSerial
//
//  Created by shanlin on 2017/6/5.
//  Copyright © 2017年 shanlin. All rights reserved.
//

import UIKit
private let kCellId = "kCellId"

private let kColumn: CGFloat = 4
private let kLeftMargin: CGFloat = 13
private let kRightMargin: CGFloat = 12
private let kMiddleMargin: CGFloat = 10
private let kSizeW: CGFloat = (UIScreen.main.bounds.width - kLeftMargin - kRightMargin - (kColumn - 1) * kMiddleMargin) / kColumn

class XJBaseVC: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!
    fileprivate lazy var newImages: [UIImage] = [UIImage]()

    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: kSizeW, height: kSizeW)
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 10
        layout.sectionInset = UIEdgeInsetsMake(9, 13, 9, 12)
        layout.scrollDirection = .vertical
    }
}

extension XJBaseVC {
    fileprivate func setupUI() {
        navigationItem.title = "连拍相机"
        view.backgroundColor = UIColor.random()
        
        collectionView.register(UINib(nibName: "XJBaseCell", bundle: nil), forCellWithReuseIdentifier: kCellId)
    }
}

extension XJBaseVC {
    @IBAction func btnClick() {
        let vc = XJCameraVC(maxAllowPhotos: 10)
//        vc.returnImagesBlock = { [unowned self] (images) in
//            self.newImages = images
//            self.collectionView.reloadData()
//        }
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
        
        vc.xj_cameraDidFinishedCallBack(self.newImages) { (images) in
            self.newImages = images
            self.collectionView.reloadData()
        }
    }
}

extension XJBaseVC: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return newImages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCellId, for: indexPath) as! XJBaseCell
        cell.imageV.image = self.newImages[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("点击第\(indexPath.item)个东西")
    }
}
